package fun.xinnix.service.impl;

import cn.hutool.core.exceptions.ValidateException;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import entity.SysUser;
import fun.xinnix.common.RequestUserInfo;
import fun.xinnix.constants.RedisKeyConstant;
import fun.xinnix.mapper.SysUserMapper;
import fun.xinnix.service.AuthService;
import fun.xinnix.utils.RedisUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class AuthServiceImpl implements AuthService {
    @Resource
    SysUserMapper sysUserMapper;
    @Resource
    RedisUtil redisUtil;

    @Override
    public String shiroLogin(String userName, String password) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(userName, password);
        subject.login(usernamePasswordToken);
        String uuid = IdUtil.fastUUID();

        return uuid;
    }

    @Override
    public String login(String userName, String password) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getUserName, userName).last("limit 1");
        SysUser sysUser = sysUserMapper.selectOne(queryWrapper);
        if (sysUser == null) {
            throw new ValidateException("账号有误");
        }
        if (!password.equals(sysUser.getPassword())) {
            throw new ValidateException("密码有误");
        }
        String uuid = IdUtil.fastUUID();
        RequestUserInfo userInfo = new RequestUserInfo();
        userInfo.setId(sysUser.getId());
        userInfo.setUserName(sysUser.getUserName());
        redisUtil.setCacheObject(RedisKeyConstant.getUserToken(uuid), userInfo);
        return uuid;
    }
}
